package com.sunfeng.n6;

import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author sunfeng
 * @date 2021/04/14 13:39
 **/
public class DecimalAccountSafeCas implements DecimalAccount {

    AtomicReference<BigDecimal> reference;

    public DecimalAccountSafeCas(BigDecimal bigDecimal) {
        this.reference = new AtomicReference<>(bigDecimal);
    }

    @Override
    public BigDecimal getBalance() {

        return reference.get();
    }

    @Override
    public void withdraw(BigDecimal amount) {
        while (true) {
            BigDecimal prev = reference.get();
            BigDecimal next = prev.subtract(amount);
            if (reference.compareAndSet(prev, next)) {
                break;
            }
        }
    }
}
